import React from "react";
import { observer, inject } from 'mobx-react';
import { WeaTop, WeaRightMenu, WeaTab, WeaFormItem, WeaSearchGroup, WeaLocaleProvider,WeaDialog } from "ecCom";
import {LogListStore} from "../../stores/list/LogListStore";
import { Button, Checkbox, Table,Menu, Dropdown} from "antd";
import { toJS } from "mobx";
import { WeaSwitch } from "comsMobx";
const CheckboxGroup = Checkbox.Group;
import jQuery from "jquery";
import { LogDetailDialog } from "./logDetail"
import { MainFieldLogDialog } from "./MainFieldLog";
import { DetailFieldLogDialog } from "./DetailFieldLog";
const getLabel = WeaLocaleProvider.getLabel;
export interface LogListProps {
    cubeLogList: LogListStore;
}

@inject("cubeLogList")
@observer
export default class LogList extends React.Component<LogListProps, any>{
    constructor(props) {
        super(props);
        this.state = {
            height: 0,
            deldata:''
        }
    }
    componentDidMount() {
        this.scrollheigth(35);
        jQuery(window).resize(() => {
            this.scrollheigth()
        });
    }
    onRightMenuClick = (key) => {
        const { cubeLogList } = this.props;
        if (key == "0") {
            cubeLogList.doSearch();
        } else if (key == '1') {
            window.close();
        }
    }

    render() {
        const { cubeLogList } = this.props;
        const { title, loading, baseParams,iconInfo } = cubeLogList;
        if(title != ''){
            document.title = title;
        }
        const rightMenus = [{
            icon: <i className='icon-coms-search' />,
            content: getLabel(197, "搜索"),
            key: 0
        }, {
            icon: <i className='icon-coms-go-back' />,
            content: getLabel(309, "关闭"),
            key: 1
        }];
        if (baseParams.hidetop&&baseParams.hidetop=="1") {
            return (
                <div className="cube-log-list">
                    <WeaRightMenu datas={rightMenus}
                                  onClick={this.onRightMenuClick}
                                  collectParams={{
                                      "favname": "",
                                      "link": '/' + window.location.toString().split('/').slice(3).join('/'),
                                      "favouritetype": 5,
                                      "importantlevel": 1
                                  }}
                    >
                       {this.getComp()}
                    </WeaRightMenu>
                </div>
            )
        }
        return (

            <div className="cube-log-list">
                <WeaRightMenu datas={rightMenus} onClick={this.onRightMenuClick}
                              collectParams={{
                                  "favname": title,
                                  "link": '/' + window.location.toString().split('/').slice(3).join('/'),
                                  "favouritetype": 5,
                                  "importantlevel": 1
                              }}>
                    <WeaTop
                        title={title}
                        loading={loading}
                        icon={<i className={iconInfo.icon} style={{color:iconInfo.iconColor}} />}
                        iconBgcolor={iconInfo.iconBg}
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={rightMenus}
                        onDropMenuClick={this.onRightMenuClick}
                    >
                        {this.getComp()}
                    </WeaTop>
                </WeaRightMenu>
            </div>
        )
    }

    search =()=>{
        const { cubeLogList } = this.props;
        cubeLogList.table.current=1;
        cubeLogList.doSearch();
        cubeLogList.setShowSearchAd(false)
    }

    getComp =()=>{
        const { cubeLogList } = this.props;
        const { showSearchAd, tableData, table,iconInfo } = cubeLogList;
        const searchButtons = [
            (<Button type="primary" onClick={this.search}>{getLabel(197, "搜索")}</Button>),
            (<Button type="ghost" onClick={() => cubeLogList.clearFormFields()}>{getLabel(2022, "重置")}</Button>),
            (<Button type="ghost" onClick={() => cubeLogList.setShowSearchAd(false)}>{getLabel(201, "取消")}</Button>)
        ];
        return <div>
             <WeaTab
                buttonsAd={searchButtons}
                searchType={['advanced']}
                setShowSearchAd={bool => { cubeLogList.setShowSearchAd(bool) }}
                hideSearchAd={() => cubeLogList.setShowSearchAd(false)}
                searchsAd={this.getFormTems()}
                advanceHeight={180}
                showSearchAd={showSearchAd}
            />
            <Table
                columns={this.getColumns()}
                className="cube-log-list-table"
                pagination={{
                    current: table.current,
                    pageSizeOptions: ['10', '20', '30', '40', '50', '100'],
                    total: tableData.total,
                    defaultPageSize: table.pagesize,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => {
                        return ` ${getLabel(18609, "共") + total+' ' + getLabel(18256, "条")} `;
                    },
                    onShowSizeChange: (current, pageSize) => { cubeLogList.changePageSize(current, pageSize) }
                }}
                onChange={cubeLogList.nextDatas}
                dataSource={toJS(tableData.logData)}
                {...this.getScrollConfig()}
            />
            <LogDetailDialog LogListStore={cubeLogList} />
            <MainFieldLogDialog cubeLogList={cubeLogList}></MainFieldLogDialog>
            <DetailFieldLogDialog cubeLogList={cubeLogList}></DetailFieldLogDialog>
            <WeaDialog
                onCancel={this.closeDelDialog}
                title={getLabel('522702','数据详情') }
                visible={cubeLogList.delLog_visible}
                iconBgcolor={iconInfo.iconBg || "#96358a"}
                icon={iconInfo.icon ||'icon-coms-ModelingEngine'}
                iconFontColor={iconInfo.iconColor || "#fff"}
                style={{ width: 500, height: 300 }}
                buttons={this.getButtons()}
                hasScroll
            >
                <p style={{margin:'15px 0px 15px 20px'}}>{getLabel('522703','数据详情为')+"：" }</p>
                {/* <div dangerouslySetInnerHTML={{ __html:this.getBeautifulJson() }}></div> */}
                <pre style={{marginLeft:20,overflow:'scroll'}} id="jsonPre"  dangerouslySetInnerHTML={{ __html:this.formatJson(this.state.deldata) }}></pre>
            </WeaDialog>
        </div>
    }

    getBeautifulJson =()=>{
        const str=this.state.deldata;
        return this.formatJson(str);
    }

    closeDelDialog =()=>{
        const { cubeLogList } = this.props;
        cubeLogList.delLog_visible=false;
    }

    recoverData = ()=>{
        const { cubeLogList } = this.props;
        cubeLogList.recoverData();
    }

    getButtons =()=>{
        const { cubeLogList } = this.props;
        const {currentType} =cubeLogList;
        let buttons=new Array();
        buttons.push( <Button type="primary" onClick={this.closeDelDialog}>{getLabel(309, '关闭')}</Button>);
        if(currentType=='3'){
            buttons.unshift( <Button type="primary" onClick={this.recoverData}>{getLabel('522756','数据恢复') }</Button>);
        }
        return buttons;
    }
    

    getColumns = ()=>{
        const { cubeLogList } = this.props;
        const {operateButton,isBackLog } = cubeLogList;
        let detailLog = operateButton && operateButton.length;
        let dropdownShow = "";
        if(detailLog ==0 || detailLog == undefined){
            dropdownShow = "none";
        }
        let width=["20%","15%","15%","18%","20%","10%"];
        if(isBackLog){
            width=["15%","15%","15%","15%","15%","10%"];
        }
        let columns=[
            { title: getLabel(99, "操作者"), dataIndex: 'operator', key: 'operator', width: width[0] },
            { title: getLabel(97, "日期"), dataIndex: 'operatedate', key: 'operatedate', width: width[1]  },
            { title: getLabel(277, "时间"), dataIndex: 'operatetime', key: 'operatetime', width: width[2]  },
            { title: getLabel(63, "类型"), dataIndex: 'operatedesc', key: 'operatedesc', width: width[3] },
            { title: 'IP', dataIndex: 'clientaddress', key: 'clientaddress', width: "20%" },
            { title:'',width: width[4] ,dataIndex: 'id',render: (id, record) =>{
                if(record.operatetype=='3'||record.operatetype=='6'){//删除
                    return <a href='javascript:void(0)' onClick={()=>this.showDeleteInfo(record.deldata,id,record.operatetype)}>{getLabel('22045','详情') }</a>
                }else{
                    return <Dropdown overlay={this.getMenu(id,record)}>
                        <a className="ant-dropdown-link" style={{display:dropdownShow}}>
                            <span className="icon-coms-more"></span>
                        </a>
                    </Dropdown>}
                }
            }
        ];
        if(isBackLog){
            columns.unshift({ title: getLabel(81287,'数据ID'), dataIndex: 'relatedid', key: 'relatedid', width: "10%" });
        }
        return columns;
    }

    showDeleteInfo = (deldata,logid,operatetype)=>{
        const { cubeLogList } = this.props;
        this.setState({deldata:deldata});
        cubeLogList.delLog_visible=true;
        cubeLogList.logid=logid;
        cubeLogList.currentType=operatetype
    }

     getMenu = (id,record) => {
        const { cubeLogList } = this.props;
        return <Menu>
            {record.orderList.map(item=>{
                return <Menu.Item>
                    <a onClick={() => {
                        if(item['key']==''){
                            cubeLogList.showMainFieldLog(id,record.relatedid);
                        }else{
                            cubeLogList.showDetailFieldLog(id,item['key'],record.relatedid);
                        }
                    }}>{item['showname']}</a>
                </Menu.Item>
            })}
        </Menu>
    };


    getFormTems = () => {
        const { cubeLogList } = this.props;
        const { condition, form, checkValues } = cubeLogList;
        const { isFormInit } = form;
        let group: any[] = [];
        isFormInit && toJS(condition).map(c => {
            let items: any[] = [];
            c.items.map((fields) => {
                let dom;
                if (fields.domkey[0] == "handletype") {
                    dom = <div><CheckboxGroup options={fields.options} value={cubeLogList.objToArr(toJS(checkValues))} onChange={cubeLogList.onCheckGroupChange} /></div>
                } else {
                    dom = <WeaSwitch fieldConfig={fields} form={form} />
                }
                items.push({
                    com: (<WeaFormItem
                        label={`${fields.label}`}
                        labelCol={{ span: `${fields.labelcol}` }}
                        wrapperCol={{ span: `${fields.fieldcol}` }}>
                        {dom}
                    </WeaFormItem>),
                    colSpan: 1,
                })
            });
            group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />)
        });
        return group;
    }

    getScrollConfig() {
        let scroll: any = {}, { height } = this.state;
        scroll.scroll = {}
        scroll.scroll.y = height;
        return scroll;
    }

    scrollheigth(h = 0) {
        let widowClientHeight = document.documentElement.clientHeight || 0;
        let titileHeight = jQuery(".ant-table-header .ant-table-thead").height() || 45;
        let bottom = (jQuery(".ant-pagination.ant-table-pagination").height() || 30) + 15;
        let scrollheigth = widowClientHeight - titileHeight - bottom - 98;
        this.setState({
            height: scrollheigth - 15 - h
        })
    }


    formatJson(str) {
        if(str==''){
            return str;
        }
        // 设置缩进为2个空格
        str = JSON.stringify(JSON.parse(str), null, 4);
        str = str
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
        return str.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, (match)=>{
            var cls = 'color: darkorange';
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = 'color: red';
                } else {
                    cls = 'color: green';
                }
            } else if (/true|false/.test(match)) {
                cls = 'color: blue';
            } else if (/null/.test(match)) {
                cls = 'color: magenta';
            }
            return '<span style="' + cls + '">' + match + '</span>';
        });
    }
}

